package com.rainkaze.lifeharbor.tools.saying;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.rainkaze.lifeharbor.databinding.ActivityToolSayingBinding;
import com.rainkaze.lifeharbor.tools.saying.model.SayingData;
import com.rainkaze.lifeharbor.tools.saying.model.SayingResponse;
import com.rainkaze.lifeharbor.tools.yiyan.model.YiYanData;
import com.rainkaze.lifeharbor.tools.yiyan.model.YiYanResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class SayingActivity extends AppCompatActivity {

    private static final String TAG = "SayingActivity";
    private static final String API_TOKEN = "LwExDtUWhF3rH5ib";
    private static final String API_BASE_URL = "https://v2.alapi.cn/api/mingyan";

    // 声明 Binding 对象
    private ActivityToolSayingBinding binding;

    private OkHttpClient okHttpClient;
    private Map<String, String> categoryTypes;
    private String currentSelectedTypeCode = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 使用 View Binding 初始化视图
        binding = ActivityToolSayingBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化 OkHttpClient
        okHttpClient = new OkHttpClient();

        // Toolbar 设置
        setSupportActionBar(binding.toolbarYiyan);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

        setupYiYanTypes();
        setupSpinner();

        binding.buttonRefreshYiyan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchYiYan();
            }
        });
    }

    private void setupYiYanTypes() {
        categoryTypes = new LinkedHashMap<>();
        // 按照 "中文名称" - "数字编号" 的格式添加数据
        categoryTypes.put("爱情", "1");
        categoryTypes.put("道德", "2");
        categoryTypes.put("青春", "3");
        categoryTypes.put("愿望", "4");
        categoryTypes.put("集体", "5");
        categoryTypes.put("理想", "6");
        categoryTypes.put("志向", "7");
        categoryTypes.put("人才", "8");
        categoryTypes.put("谦虚", "9");
        categoryTypes.put("人格", "10");
        categoryTypes.put("天才", "11");
        categoryTypes.put("青年", "12");
        categoryTypes.put("社会", "13");
        categoryTypes.put("国家", "14");
        categoryTypes.put("财富", "15");
        categoryTypes.put("智慧", "16");
        categoryTypes.put("修养", "17");
        categoryTypes.put("工作", "18");
        categoryTypes.put("妇女", "19");
        categoryTypes.put("儿童", "20");
        categoryTypes.put("思想", "21");
        categoryTypes.put("理智", "22");
        categoryTypes.put("学习", "23");
        categoryTypes.put("科学", "24");
        categoryTypes.put("信仰", "25");
        categoryTypes.put("诚信", "26");
        categoryTypes.put("读书", "27");
        categoryTypes.put("成败", "28");
        categoryTypes.put("奉献", "29");
        categoryTypes.put("劳动", "30");
        categoryTypes.put("节约", "31");
        categoryTypes.put("教育", "32");
        categoryTypes.put("企业", "33");
        categoryTypes.put("事业", "34");
        categoryTypes.put("时间", "35");
        categoryTypes.put("勤奋", "36");
        categoryTypes.put("民族", "37");
        categoryTypes.put("真理", "38");
        categoryTypes.put("友谊", "39");
        categoryTypes.put("自由", "40");
        categoryTypes.put("心理", "41");
        categoryTypes.put("心灵", "42");
        categoryTypes.put("人生", "43");
        categoryTypes.put("幸福", "44");
        categoryTypes.put("团结", "45");
    }

    private void setupSpinner() {
        List<String> typeNames = new ArrayList<>(categoryTypes.keySet());
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, typeNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spinnerYiyanType.setAdapter(adapter);

        binding.spinnerYiyanType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedTypeName = parent.getItemAtPosition(position).toString();
                currentSelectedTypeCode = categoryTypes.get(selectedTypeName);
                fetchYiYan();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        if (!typeNames.isEmpty()) {
            binding.spinnerYiyanType.setSelection(0);
            currentSelectedTypeCode = categoryTypes.get(typeNames.get(0));
        }
    }

    private void fetchYiYan() {
        binding.progressBarYiyan.setVisibility(View.VISIBLE);
        binding.textViewHitokoto.setText("正在加载名人名言...");
        binding.textViewFrom.setText("");
        binding.textViewCreator.setText("");
        binding.textViewCreator.setVisibility(View.GONE);



        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_BASE_URL).newBuilder();
        urlBuilder.addQueryParameter("token", API_TOKEN);
        if (currentSelectedTypeCode != null && !currentSelectedTypeCode.isEmpty()) {
            urlBuilder.addQueryParameter("type", currentSelectedTypeCode);
        }
        String apiUrl = urlBuilder.build().toString();

        Log.d(TAG, "名人名言请求URL: " + apiUrl);

        Request request = new Request.Builder()
                .url(apiUrl)
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "请求失败 ", e);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.progressBarYiyan.setVisibility(View.GONE);
                        binding.textViewHitokoto.setText("网络请求失败");
                        Toast.makeText(SayingActivity.this, "网络错误: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        throw new IOException("返回结果为空");
                    }
                    responseBodyString = responseBody.string();
                }

                if (!response.isSuccessful()) {
                    Log.e(TAG, "API请求错误: " + response.message() + ", code: " + response.code() + ", body: " + responseBodyString);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.progressBarYiyan.setVisibility(View.GONE);
                            binding.textViewHitokoto.setText("获取失败: " + response.code() + " " + response.message());
                            Toast.makeText(SayingActivity.this, "获取名人名言失败: " + response.code(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return;
                }

                Log.d(TAG, "名人名言请求返回结果: " + responseBodyString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.progressBarYiyan.setVisibility(View.GONE);
                        try {
                            Gson gson = new Gson();
                            SayingResponse sayingResponse = gson.fromJson(responseBodyString, SayingResponse.class);

                            if (sayingResponse != null && sayingResponse.getCode() == 200 && sayingResponse.getData() != null) {
                                SayingData data = sayingResponse.getData();
                                binding.textViewHitokoto.setText(data.getContent());
                                String fromText = "—— " + (data.getAuthor() != null ? data.getAuthor() : "未知来源");
                                binding.textViewFrom.setText(fromText);

                            } else {
                                String errorMsg = "获取失败";
                                if (sayingResponse != null && sayingResponse.getMessage() != null) {
                                    errorMsg += ": " + sayingResponse.getMessage();
                                } else if (sayingResponse != null) {
                                    if(sayingResponse.getCode() == 429) {
                                        errorMsg += "请求次数过多，请稍后再试";
                                    }else{
                                        errorMsg += "未知错误，错误代码"+sayingResponse.getCode();
                                    }
                                }
                                binding.textViewHitokoto.setText(errorMsg);
                                Log.e(TAG, "API错误或违法数据: " + errorMsg);
                                Toast.makeText(SayingActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "JSON格式错误: ", e);
                            binding.textViewHitokoto.setText("解析数据失败");
                            Toast.makeText(SayingActivity.this, "数据处理错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}